package com.example.handle;


import com.example.exception.BaseException;
import com.example.result.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.sql.SQLIntegrityConstraintViolationException;

/**
 * 全局异常处理器，处理项目中抛出的业务异常
 */
@RestControllerAdvice
@Slf4j
public class GlobalException {
    /**
     * 捕获业务异常
     * @param ex
     * @return
     */
    @ExceptionHandler
    public Result exceptionHandler(BaseException ex){
        log.error("异常信息：{}", ex.getMessage());
        return Result.error(ex.getMessage());
    }

    /**
     * 用户名重复异常 手机号输入错误 身份证号输入重复
     */
    @ExceptionHandler
    public Result usernameExceptionHandle(SQLIntegrityConstraintViolationException ex){
        String message=ex.getMessage();
        if(message.contains("idx_username")){
            String msg="用户名已存在";
            return  Result.error(msg);
        } else if (message.contains("employee.employee_phone_uindex")) {
            return Result.error("手机号输入错误");
        }
        else if (message.contains("employee.employee_id_number_uindex")) {
            return Result.error("身份证号输入错误");
        }
        else{
            return Result.error("未知错误");
        }
    }
}
